    //
//  AddNewPersonViewController.m
//  BVCMS
//
//  Created by Allen Thomas on 11/9/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "AddNewPersonViewController.h"
#import "MemberCheckinViewController.h"
#import "TextFieldCell.h"
#import "SegmentedCell.h"

@implementation AddNewPersonViewController

#define CheckInViewController [[self.navigationController viewControllers] objectAtIndex:1]

@synthesize person, theTableView, actifText;

- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = @"Add Person";
	
	// Register notification when the keyboard will be show
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWillShow:)
												 name:UIKeyboardWillShowNotification
											   object:nil];
	
    // Register notification when the keyboard will be hide
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWillHide:)
												 name:UIKeyboardWillHideNotification
											   object:nil];
	
	
	UIBarButtonItem* commitButton = [[UIBarButtonItem alloc] initWithTitle:@"Commit" style:UIBarButtonItemStylePlain target:self action:@selector(commit:)];
	self.navigationItem.rightBarButtonItem = commitButton;
	[commitButton release];
	
	fields = [[NSMutableArray alloc] initWithCapacity:1];
	
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"First Name",@"title", 
					   @"",@"placeholder", 
					   @"textfield",@"type",
					   nil] ];
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"Goes By",@"title", 
					   @"",@"placeholder", 
					   @"textfield",@"type",
					   nil] ];
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"Last Name",@"title", 
					   @"",@"placeholder", 
					   @"textfield",@"type",
					   nil] ];
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"Date of Birth",@"title", 
					   @"mm/dd/yy",@"placeholder", 
					   @"textfield",@"type",
					   nil] ];
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"Cell Phone",@"title", 
					   @"10 digits",@"placeholder", 
					   @"textfield",@"type",
					   nil] ];
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"Email",@"title", 
					   @"",@"placeholder", 
					   @"textfield",@"type",
					   nil] ];
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"Gender",@"title", 
					   @"",@"placeholder", 
					   @"segmented",@"type",
					   [NSArray arrayWithObjects: @"Male", @"Female", nil],@"options",
					   nil] ];
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"Marital",@"title", 
					   @"",@"placeholder", 
					   @"segmented",@"type",
					   [NSArray arrayWithObjects: @"Single", @"Married", nil],@"options",
					   nil] ];
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"Home Phone",@"title", 
					   @"10 digits",@"placeholder", 
					   @"textfield",@"type",
					   nil] ];
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"Address",@"title", 
					   @"",@"placeholder", 
					   @"textfield",@"type",
					   nil] ];
	[fields addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					   @"Zip",@"title", 
					   @"5 digits",@"placeholder", 
					   @"textfield",@"type",
					   nil] ];
	
	cells = [[NSMutableArray alloc] initWithCapacity:[fields count]];

	for (int i=0; i < [fields count]; i++) {
		[cells addObject:[self createCell:i]];
	}

}

- (BOOL)checkFields {
	NSPredicate *predicate;
		
	TextFieldCell *firstNameCell = (TextFieldCell*)[cells objectAtIndex:0];
	if( [firstNameCell.valueTextField.text length] == 0) {
		UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Required Field" message:@"First Name is Required" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[connectionError show];
		[connectionError release];	
		return NO;
	}
	
	TextFieldCell *lastNameCell = (TextFieldCell*)[cells objectAtIndex:2];
	if( [lastNameCell.valueTextField.text length] == 0) {
		UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Required Field" message:@"Last Name is Required" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[connectionError show];
		[connectionError release];	
		return NO;
	}
	
	TextFieldCell *dobCell = (TextFieldCell*)[cells objectAtIndex:3];
	NSString *dobRegEx = @"^(0[1-9]|1[012]|[1-9])/(0[1-9]|[12][0-9]|3[01]|[1-9])/[0-9]{2}$";
	predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", dobRegEx];
	if( [dobCell.valueTextField.text length] == 0 || ![predicate evaluateWithObject:dobCell.valueTextField.text]) {
		UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Required Field" message:@"Date of Birth (mm/dd/yy) is Required" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[connectionError show];
		[connectionError release];	
		return NO;
	}
	
	TextFieldCell *cellphoneCell = (TextFieldCell*)[cells objectAtIndex:4];
	TextFieldCell *emailCell = (TextFieldCell*)[cells objectAtIndex:5];
	NSString *emailRegEx = @"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?";
	predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
	if( [emailCell.valueTextField.text length] == 0 || ![predicate evaluateWithObject:emailCell.valueTextField.text]) {
		UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Required Field" message:@"A valid email address is Required" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[connectionError show];
		[connectionError release];
		return NO;
	}
	
	TextFieldCell *homephoneCell = (TextFieldCell*)[cells objectAtIndex:8];
	if( [cellphoneCell.valueTextField.text length] == 0 && [homephoneCell.valueTextField.text length] == 0 ) {
		UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Required Field" message:@"Cell or Home Phone is Required" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[connectionError show];
		[connectionError release];		
		return NO;
	}

	return YES;
}

- (void)commit:(id)sender {
	NSLog(@"commit");
		
	if([self checkFields] == 1) {
		TextFieldCell *firstNameCell = (TextFieldCell*)[cells objectAtIndex:0];	
		TextFieldCell *goesByCell = (TextFieldCell*)[cells objectAtIndex:1];
		TextFieldCell *lastNameCell = (TextFieldCell*)[cells objectAtIndex:2];
		TextFieldCell *dobCell = (TextFieldCell*)[cells objectAtIndex:3];
		TextFieldCell *cellphoneCell = (TextFieldCell*)[cells objectAtIndex:4];
		TextFieldCell *emailCell = (TextFieldCell*)[cells objectAtIndex:5];
		SegmentedCell *genderCell = (SegmentedCell*)[cells objectAtIndex:6] ;
		SegmentedCell *maritalCell = (SegmentedCell*)[cells objectAtIndex:7];
		TextFieldCell *homephoneCell = (TextFieldCell*)[cells objectAtIndex:8];
		TextFieldCell *addressCell = (TextFieldCell*)[cells objectAtIndex:9];
		TextFieldCell *zipCell = (TextFieldCell*)[cells objectAtIndex:10];
		
		NSString *addtofamilyid = @"0";
		if( [person valueForKey:@"peopleid"] ) {
			addtofamilyid = [person valueForKey:@"peopleid"];
		}
		
		NSString *marital = @"10";
		if( maritalCell.valueSegmented.selectedSegmentIndex == 1) 
			marital = @"20";
		
		NSString *gender = @"1";
		if( genderCell.valueSegmented.selectedSegmentIndex == 1 )
			gender = @"2";
		
		NSString *goesby = @"";
		if( [goesByCell.valueTextField.text length] > 0 ) {
			goesby = goesByCell.valueTextField.text;
		}
		
		NSString *address = @"";
		if( [addressCell.valueTextField.text length] > 0 ) {
			address = addressCell.valueTextField.text;
		}
		
		NSString *zip = @"";
		if( [zipCell.valueTextField.text length] > 0 ) {
			zip = zipCell.valueTextField.text;
		}
		
		
		NSString *paramString = [NSString stringWithFormat:@"addtofamilyid=%@&addr=%@&zip=%@&first=%@&last=%@&goesby=%@&dob=%@&email=%@&cell=%@&home=%@&marital=%@&gender=%@",
			  addtofamilyid,address,zip,firstNameCell.valueTextField.text,
			  lastNameCell.valueTextField.text, goesby, dobCell.valueTextField.text, 
			  emailCell.valueTextField.text, cellphoneCell.valueTextField.text, homephoneCell.valueTextField.text,
			  marital, gender];
		
		NSLog(@"Sending notification");

		[CheckInViewController addNewPerson:paramString];
		
		[self.navigationController popToViewController:CheckInViewController animated:YES]; 
	}
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [fields count];
}

		 
- (UITableViewCell *) createCell:(int)row {
	NSDictionary *field = [fields objectAtIndex:row];
	
    NSString *CellIdentifier = [NSString stringWithFormat: @"Cell%i", row];
    
	if ([[field valueForKey:@"type"] isEqual:@"textfield"]) {
		TextFieldCell *cell = (TextFieldCell *)[theTableView  dequeueReusableCellWithIdentifier:CellIdentifier];
		if (cell == nil) {
			NSLog(@"New");
			cell = [[[NSBundle mainBundle] loadNibNamed:@"TextFieldCell" owner:self options:nil] objectAtIndex:0];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			
			cell.valueTextField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
			cell.valueTextField.autocapitalizationType = UITextAutocapitalizationTypeWords; // no auto capitalization support
			// set keyboard types
			if (row == 4 || row == 8) {
				cell.valueTextField.keyboardType = UIKeyboardTypePhonePad;
			} else if (row == 5) {
				cell.valueTextField.keyboardType = UIKeyboardTypeEmailAddress;
			} else if (row == 3) {
				cell.valueTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
			} else if (row == 10 ) {
				cell.valueTextField.keyboardType = UIKeyboardTypeNumberPad;
			}
			
			cell.titleLabel.text = [field valueForKey:@"title"];
			cell.valueTextField.placeholder = [field valueForKey:@"placeholder"];
			
			[cell.valueTextField setDelegate:self];		
			[cell.valueTextField addTarget:self action:@selector(textFieldDone:) 
						  forControlEvents:UIControlEventEditingDidEndOnExit];
			
			if( [person valueForKey:@"peopleid"] ) {
				switch (row) {
					case 8:
						cell.valueTextField.text = [person valueForKey:@"homephone"];
						break;
					case 9:
						cell.valueTextField.text = [person valueForKey:@"address"];
						break;
					case 10:
						cell.valueTextField.text = [person valueForKey:@"zip"];
						break;
					default:
						break;
				}
			} else {
				cell.valueTextField.text = [field valueForKey:@""];
			}
			cell.valueTextField.tag = row;
		}
		return cell;
	} else if ([[field valueForKey:@"type"] isEqual:@"segmented"]) {
		SegmentedCell *cell = (SegmentedCell *)[theTableView dequeueReusableCellWithIdentifier: CellIdentifier];
		if (cell == nil) {
			NSLog(@"New");
			cell = [[[NSBundle mainBundle] loadNibNamed:@"SegmentedCell" owner:self options:nil] objectAtIndex:0];
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			
			cell.titleLabel.text = [field valueForKey:@"title"];
			[cell.valueSegmented removeAllSegments];
			
			NSArray *segmentTitles = [field valueForKey:@"options"];
			for(int i = 0; i < [segmentTitles count]; i++)
			{
				[cell.valueSegmented insertSegmentWithTitle:[segmentTitles objectAtIndex:i] atIndex:i animated:NO];
			}
			
			cell.valueSegmented.frame  = CGRectMake(110, 10, 195, 25);
			cell.valueSegmented.selectedSegmentIndex = 0;
		}
		return cell;
	}
	
	return nil;
}
				 

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	return [cells objectAtIndex:indexPath.row];
}

#pragma mark Text Field Delegate Methods

// To be link with your TextField event "Editing Did Begin"
//  memoryze the current TextField
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    self.actifText = textField;
}

// To be link with your TextField event "Editing Did End"
//  release current TextField
- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    self.actifText = nil;
}

-(IBAction)textFieldDone:(id)sender{	
	NSLog(@"textFieldDone");
}

-(void) keyboardWillShow:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];
	
    // Detect orientation
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect frame = self.theTableView.frame;
	
    // Start animation
    [UIView beginAnimations:nil context:NULL];
    //[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];
	
    // Reduce size of the Table view 
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
        frame.size.height -= keyboardBounds.size.height - 49;
    else 
        frame.size.height -= keyboardBounds.size.width;
	
    // Apply new size of table view
    self.theTableView.frame = frame;
	
    // Scroll the table view to see the TextField just above the keyboard
    if (self.actifText)
	{
		NSIndexPath *ip = [NSIndexPath indexPathForRow:actifText.tag inSection:0];
        [self.theTableView scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:YES];
	}
	
    [UIView commitAnimations];
}

-(void) keyboardWillHide:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];
	
    // Detect orientation
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect frame = self.theTableView.frame;
	
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];
	
    // Reduce size of the Table view 
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
        frame.size.height += keyboardBounds.size.height - 49;
    else 
        frame.size.height += keyboardBounds.size.width;
	
    // Apply new size of table view
    self.theTableView.frame = frame;
	
    [UIView commitAnimations];
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[fields release];
	[cells release];
	[person release];
	[theTableView release];
	[actifText release];
    [super dealloc];
}


@end
